<?php

namespace GuanChanghu\Library\Repositories\Base\Traits;

use GuanChanghu\Library\Contracts\Repositories\Query;
use GuanChanghu\Library\Facades\ModelQuery;
use Illuminate\Support\Str;

/**
 * @author 管昌虎
 * Trait AutoQuery
 * @tag encryption free
 * @package GuanChanghu\Library\Repositories\Base\Traits
 * Created on 2023/4/15 21:20
 * Created by 管昌虎
 * Email guanchanghu626@163.com
 */
trait AutoQuery
{
    /**
     * 自动查询
     */
    public function autoQuery(): Query
    {
        $builder = $this->builder();
        $condition = $this->attribute()->condition();

        $condition->each(function ($value, $key) use ($builder, $condition) {
            if (in_array($key, ['id', $builder->getModel()->getKeyName(), 'name', 'title', 'content', 'detail', 'code'])) {
                ModelQuery::queryOptional($builder, $key, $condition);
            } else if (in_array($key, ['status', 'state', 'type', 'locale'], true) || str_ends_with($key, 'Id')) {
                ModelQuery::queryCongruence($builder, $key, $condition);
            } else if ($key === 'user') {
                ModelQuery::queryUserInfo($builder, $key, $condition);
            } else if (Str::startsWith($key, 'is')) {
                ModelQuery::queryIsStatus($builder, $key, $condition);
            } else if (in_array($key, ['createdAt', 'auditAt', 'refuseAt', 'refusedAt', 'startAt', 'startedAt', 'endAt', 'endedAt', 'beginAt', 'finishAt', 'updatedAt', 'deletedAt',], true)) {
                ModelQuery::queryTimeRange($builder, $key, $condition);
            } else if (str_ends_with($key, 'Range')) {
                ModelQuery::queryRange($builder, substr($key, 0, -strlen('Range')), $condition);
            } else if (str_ends_with($key, 'Optional')) {
                return true;
            } else {
                ModelQuery::queryOptional($builder, $key, $condition);
            }

            return true;
        });

        return $this;
    }
}
